package com.lanxiao.cloud.modules.dict.domain.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.common.mybatis.service.impl.BaseServiceImpl;
import com.lanxiao.cloud.modules.dict.domain.event.DictChangeEvent;
import com.lanxiao.cloud.modules.dict.domain.event.DictChangePublisher;
import com.lanxiao.cloud.modules.dict.domain.model.Dict;
import com.lanxiao.cloud.modules.dict.domain.service.IDictService;
import com.lanxiao.cloud.modules.dict.domain.service.IDictTypeService;
import com.lanxiao.cloud.modules.dict.infrastructure.error.DictErrorType;
import com.lanxiao.cloud.modules.dict.infrastructure.repository.DictMapper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ：qiaoliang
 * @date ：2021-09-26
 */
@Service
public class DictServiceImpl extends
    BaseServiceImpl<Long, DictMapper, Dict> implements
    IDictService {

  private final DictChangePublisher dictChangePublisher;
  @Autowired
  private IDictTypeService dictTypeService;

  public DictServiceImpl(
      DictChangePublisher dictChangePublisher) {
    this.dictChangePublisher = dictChangePublisher;
  }

  @Override
  public void saveDict(Dict dict) {
    BusinessException.isFalse(dictTypeService.checkDictType(dict.getType()),
        DictErrorType.DICT_TYPE_ERROR);
    this.save(dict);
    this.changeRoute();
  }

  @Override
  public void updateDict(Dict dict) {
    BusinessException.isFalse(dictTypeService.checkDictType(dict.getType()),
        DictErrorType.DICT_TYPE_ERROR);
    this.updateById(dict);
    this.changeRoute();
  }

  @Override
  public void deleteById(Long id) {
    this.removeById(id);
    this.changeRoute();
  }

  @Override
  public void deleteByType(String type) {
    List<Dict> list = this.list(new LambdaQueryWrapper<Dict>().eq(Dict::getType, type));
    if(CollUtil.isNotEmpty(list)) {
      list.forEach(l->{
        l.delete();
        this.updateById(l);
      });
    }
    this.changeRoute();
  }

  /**
   *  触发变动事件
   *
   * @author ：qiaoliang

   * @date 2021-09-26 17:02
   */
  private void changeRoute() {
    dictChangePublisher.asyncPublish(new DictChangeEvent());
  }

}
